var createError = require("http-errors")
var express = require("express")
var path = require("path")
var cookieParser = require("cookie-parser")
var logger = require("morgan")
// var http = require("http")
const bodyParser = require("body-parser")

var userRouter = require("./routes/moudles/users/users")
var myRouter = require("./routes/moudles/my/my")
var shopListRouter = require("./routes/moudles/shopList/shopList")
// var uRouter = require("./routes/users")
var homeRouter = require("./routes/moudles/home/home")
var cartRouter = require("./routes/moudles/cart/cart")
var searchRouter = require("./routes/moudles/search/search")
var payRouter = require("./routes/moudles/pay/pay")
var listRouter = require("./routes/moudles/list/list")
var orderRouter = require("./routes/moudles/order/order")
var newsRouter = require("./routes/moudles/news/news")
const cors = require("cors")

var WebSocketServer = require("ws").Server,
  wss = new WebSocketServer({ port: 8081 })
wss.on("connection", function (ws) {
  console.log("client connected")
  ws.on("message", function (message) {
    console.log(message.toString())

    ws.send(message.toString())
  })
  // ws.send("收到了")
})

var app = express()
//对body-parser进行配置
app.use(bodyParser.urlencoded({ extended: true, limit: "20mb" }))
//设置完毕之后，会在req对象上面新增一个req.body的一个对象
// parse application/x-www-form-urlencoded
// app.use(bodyParser.urlencoded({ extended: false, limit: "20mb" }))

// parse application/json
app.use(bodyParser.json())

app.use(cors()) //使用cors中间件
// view engine setup
app.set("views", path.join(__dirname, "views"))
app.set("view engine", "ejs")

app.use(logger("dev"))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, "public")))

app.use("/", userRouter)
// app.use("/", uRouter)
app.use("/", myRouter)
app.use("/", shopListRouter)
app.use("/", homeRouter)
app.use("/", cartRouter)
app.use("/", searchRouter)
app.use("/", payRouter)
app.use("/", listRouter)
app.use("/", orderRouter)
app.use("/", newsRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404))
})

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message
  res.locals.error = req.app.get("env") === "development" ? err : {}

  // render the error page
  res.status(err.status || 500)
  res.render("error")
})

module.exports = app
